const { exec } = require('child_process')

let AppActivity = 'com.ss.android.ugc.aweme/com.ss.android.ugc.aweme.splash.SplashActivity'
let log = !true

const topPoint = { x: 999, y: 955 }

const ShellFn = (command) => {
  return new Promise((resolve, reject) => {
    log && console.log('--->')
    log && console.log(command, '\n')

    exec(command, (err, stdout, stderr) => {
      if (err) reject(new Error(err + ''))
      log && console.log('result:', stdout)
      resolve(stdout)
      log && console.log('<---')
    })
  })
}

const openApp = () => {
  const shell = `adb shell am start -n ${AppActivity}`
  return ShellFn(shell)
}

const saveFile = async (key = Math.random()) => {
  const filePath = `/sdcard/screen_${key}.png`
  const SaveShell = `adb shell screencap ${filePath}`
  const saveToLocal = `adb pull ${filePath} img/screen_${key}.png`
  const RemoveShell = `adb shell rm ${filePath}`
  // return ShellFn(shell)
  await ShellFn(SaveShell)
  await ShellFn(saveToLocal)
  await ShellFn(RemoveShell)
  return key
}

const swipe = (a = { x: 300, y: 1000 }, b = { x: 300, y: 640 }, ms = 200) => {
  const { x: x1, y: y1 } = a
  const { x: x2, y: y2 } = b
  const shell = `adb shell input swipe ${x1} ${y1} ${x2} ${y2} ${ms}`
  return ShellFn(shell)
}

const touch = (point = topPoint) => {
  const { x, y } = point
  const shell = `adb shell input tap ${x} ${y}`
  return ShellFn(shell)
}

module.exports = {
  openApp,
  saveFile,
  swipe,
  touch
}
